<!-- src/views/PostInfo.vue -->
<template>
  <div class="post-detail">
    <!-- 返回按钮 -->
    <el-button type="text" class="back-button" @click="goBack">返回</el-button>

    <!-- 删除按钮 -->
    <el-button
        type="danger"
        class="delete-button"
        @click="deletePost"
        v-if="isPostOwner"
    >
      删除帖子
    </el-button>

    <!-- 帖子头部 -->
    <div class="post-header">
      <h2 class="post-title">{{ post.title }}</h2> <!-- 添加帖子标题 -->
      <div class="author-info">
        <span class="author-name">{{ post.userName }}</span>
        <span class="post-time">{{ formatDate(post.date) }}</span>
      </div>
    </div>

    <!-- 帖子内容 -->
    <div class="post-content">
      <p>{{ post.content }}</p>
    </div>

    <!-- 帖子图片 -->
    <div v-if="post.image" class="post-image">
      <img :src="require(`../assets/uploads/${post.image}`)" alt="帖子图片" style="width: 50%; height: auto; border-radius: 4px; margin-top: 10px;" />
    </div>

    <!-- 点赞按钮和点赞数量 -->
    <div class="like-section">
      <!-- 点赞图标 -->
      <div class="like-icon-container">
        <img
          @click="toggleLike"
          :src="isLiked ?
          require('../assets/thumbs-uped.svg') : require('../assets/thumbs-up.svg')"
          alt="点赞图标"
          :class="{ 'like-animation': isAnimating }"
        >
  <!--        {{ isLiked ? '取消点赞' : '点赞' }}-->
        <!-- 粒子效果容器 -->
        <div class="particle-container" v-if="isAnimating">
          <div
              v-for="(particle, index) in particles"
              :key="index"
              class="particle"
              :style="{
              '--x': `${particle.x}px`,
              '--y': `${particle.y}px`,
              top: '50%',
              left: '50%',
            }"
          ></div>
        </div>
      </div>
      <span class="like-count">{{ post.likes || 0 }}</span>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input">
      <textarea
          v-model="newComment"
          placeholder="在这里写评论..."
      ></textarea>
      <button @click="submitComment">发布</button>
    </div>

    <!-- 评论列表 -->
    <div class="comments-section">
      <h3>评论</h3>
      <div v-if="post.commentList && post.commentList.length > 0">
        <div v-for="comment in post.commentList" :key="comment.id" class="comment">
          <div class="comment-author">{{ comment.userName }}</div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-time">{{ formatDate(comment.date) }}</div>
          <button class = "delete-comment-button"
              @click="deleteCommentt(comment.id)"
          >
<!--              v-if="isCommentOwner(comment)"-->
            删除
          </button>
        </div>
      </div>
      <div v-else class="no-more-comments">没有更多评论</div>
    </div>

  </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import { useRouter, useRoute } from 'vue-router'; // 引入 useRouter 和 useRoute
import {AddComment, DeletePost, GetPost, isLike, likePost, deleteComment} from "@/api";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: 'PostInfo',
  setup() {
    const router = useRouter(); // 获取路由实例
    const route = useRoute(); // 获取路由参数
    const newComment = ref('');
    const post = ref({
      id: '',
      userId: '',
      userName: '',
      date: '',
      title: '',
      content: '',
      image: '',
      likes: 0,
      commentList: [

      ],
    });

    // const CommentDTO = reactive({
    //   postId: '',
    //   fatherId: '',
    //   content: '',
    // });

    // 判断当前用户是否是帖子作者或者管理员
    const isPostOwner = ref(false);
    const isLiked = ref(false); // 当前用户是否已经点赞
    const isAnimating = ref(false); // 控制动画状态
    const particles = ref([]); // 粒子效果数据

    // 返回按钮点击事件
    const goBack = () => {
      router.push('/community'); // 跳转到社区页面
    };

    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleString();
    };

    // const fetchImage = () => {
    //   if(post.value.image){
    //     const image = `http://localhost:8082/uploads/${post.value.image}`;
    //     console.log('image::', image)
    //     console.log('token::', localStorage.getItem('token'))
    //     return GetImage(image);
    //   }
    // }

    //删除评论
    const deleteCommentt = async (commentId) => {
      try {
        // await ElMessageBox.confirm('确定要删除该评论吗？', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning',
        // });

        const response = await deleteComment(commentId);
        if (response.data.code === 200) {
          ElMessage.success("评论删除成功");
          post.value.commentList = post.value.commentList.filter(comment => comment.id !== commentId);
          setTimeout(() => {
            fetchPost();
            checkIfLiked(route.params.postId);
          }, 500)
        } else {
          ElMessage.error("删除失败：" + response.data.errorMsg);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error("删除评论失败:", error);
          ElMessage.error("删除评论失败");
        }
      }
    };

    // 获取帖子详情
    const fetchPost = async () => {
      const postId = route.params.postId;
      console.log('postId:', postId);
      try {
        const response = await GetPost(postId);
        // console.log('imageUrl', response.data.data.image)
        console.log('GetPost Response:', response); // 添加调试信息
        if (response.data.code === 200) {
          post.value = response.data.data;
          // 判断当前用户是否是帖子作者
          const currentUserId = localStorage.getItem('userId');
          if ((currentUserId && post.value.userId === parseInt(currentUserId))) {
            isPostOwner.value = true;
          }else if(localStorage.getItem('type') === '0'){
            isPostOwner.value = true;
          }
          console.log('post.value.userId', post.value.userId);
          console.log('currentUserId:', currentUserId);
          console.log('type:', localStorage.getItem('type'))
          console.log('isPostOwner:', isPostOwner.value);
          // try {
          //   const url = `http://localhost:8081/community/${post.value.image}`;
          //   // 发送请求获取图片二进制数据
          //   const response = GetImage(url, {
          //     responseType: 'arraybuffer', // 指定响应类型为二进制数据
          //   });
          //
          //   // 将二进制数据转换为 Blob 对象
          //   const blob = new Blob([response.data], { type: response.headers['content-type'] });
          //
          //   // 生成可用的 URL
          //   this.imageUrl = URL.createObjectURL(blob);
          // } catch (error) {
          //   console.error('Failed to load image:', error);
          // }
        } else {
          ElMessage.error("获取帖子详情失败");
        }
      } catch (error) {
        console.error("获取帖子详情失败:", error);
        ElMessage.error("请求失败，请稍后重试");
      }
    };

    // 检查当前用户是否已经点赞
    const checkIfLiked = async (postId) => {
      try {
        const response = await isLike(postId);
        if (response.data.code === 200) {
          if (response.data.data === "1"){
            isLiked.value = true;
          }else{
            isLiked.value = false;
          }
          // isLiked.value = response.data.data === "1"; // "1" 表示已点赞
        }
        console.log('response',response)
      } catch (error) {
        console.error("检查点赞状态失败:", error);
      }
    };

    // 生成粒子效果
    const generateParticles = () => {
      const particleCount = 10; // 粒子数量
      const newParticles = [];
      for (let i = 0; i < particleCount; i++) {
        const angle = (Math.random() * 360) * (Math.PI / 180);
        const distance = Math.random() * 50 + 50; // 粒子飞散距离
        newParticles.push({
          x: Math.cos(angle) * distance,
          y: Math.sin(angle) * distance,
        });
      }
      particles.value = newParticles;
    };

    // 点赞或取消点赞
    const toggleLike = async () => {
      try {
        const response = await likePost(post.value.id);
        if (response.data.code === 200) {
          await fetchPost();
          // isLiked.value = !isLiked.value; // 切换点赞状态
          await checkIfLiked(post.value.id);
          // post.value.likes += isLiked.value ? 1 : -1; // 更新点赞数量
          // ElMessage.success(isLiked.value ? "点赞成功" : "取消点赞成功");

          // 触发点赞动画
          isAnimating.value = true;
          generateParticles();
          setTimeout(() => {
            isAnimating.value = false;
            particles.value = [];
          }, 1000); // 动画持续 1 秒
        } else {
          ElMessage.error("操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    };

    // 删除帖子
    const deletePost = async () => {
      try {
        // 弹出确认对话框
        await ElMessageBox.confirm('确定要删除该帖子吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        const postId = route.params.postId;
        const response = await DeletePost(postId);
        if (response.data.code === 200) {
          ElMessage.success("帖子删除成功");
          await router.push('/community'); // 跳转回社区页面
        } else {
          ElMessage.error("删除帖子失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error("删除帖子失败:", error);
          ElMessage.error("删除帖子失败");
        }
      }
    };

    // 提交评论
    const submitComment = async () => {
      if (newComment.value.trim()) {
        try {
          // 创建评论数据对象
          const commentData = {
            postId: route.params.postId,
            fatherId: '0', // 根据实际情况设置父评论ID
            content: newComment.value,
          };

          // 调用 AddComment 方法发送评论数据到后端
          const response = await AddComment(commentData);
          if (response.data.code === 200) {
            ElMessage.success("评论发布成功");
            // 清空评论输入框
            newComment.value = '';
            // 刷新评论列表（如果需要）
            await fetchPost();
          } else {
            ElMessage.error("评论发布失败");
          }
        } catch (error) {
          console.error("评论发布失败:", error);
          ElMessage.error("评论发布失败");
        }
      } else {
        ElMessage.warning("评论内容不能为空");
      }
    };

    // const loadImage = () => {
    //   try {
    //     const url = `http://localhost:8081/community/${post.value.image}`;
    //     // 发送请求获取图片二进制数据
    //     const response = GetImage(url, {
    //       responseType: 'arraybuffer', // 指定响应类型为二进制数据
    //     });
    //
    //     // 将二进制数据转换为 Blob 对象
    //     const blob = new Blob([response.data], { type: response.headers['content-type'] });
    //
    //     // 生成可用的 URL
    //     this.imageUrl = URL.createObjectURL(blob);
    //   } catch (error) {
    //     console.error('Failed to load image:', error);
    //   }
    // }

    // 页面加载时获取帖子详情
    onMounted(() => {
      fetchPost();
      checkIfLiked(route.params.postId);
      // loadImage();
    });

    return {
      newComment,
      goBack, // 返回方法
      submitComment,
      post,
      formatDate,
      isPostOwner,
      deletePost,
      isLiked,
      toggleLike,
      isAnimating,
      particles,
      generateParticles,
      // CommentDTO,
      // fetchImage,
      deleteCommentt,
    };
  },
};
</script>

<style scoped>
.post-detail {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
}

.back-button {
  position: absolute;
  font-size: 14px;
  color: #81acdc;
  cursor: pointer;
  width: 50px;
}

.delete-button {
  position: absolute;
  top: 20px;
  right: 20px;
}

.back-button:hover {
  color: #0056b3;
}

.delete-comment-button {
  font-size: 13px;
  border: none;
  cursor: pointer;
  margin: 0 10px;
}

.delete-comment-button:hover {
  color: #43678e;
}

.post-header {
  margin-top: 35px;
  margin-bottom: 20px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #333;
}

.like-section {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.like-count {
  font-size: 14px;
  color: #333;
}

.post-content {
  font-size: 16px;
  color: #333;
  line-height: 1.6;
  margin-top: 20px;
  margin-bottom: 50px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.post-image img {
  width: 100%;
  border-radius: 4px;
  margin-top: 10px;
}

.comments-section {
  margin-bottom: 20px;
}

.comment {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.comment:last-child {
  border-bottom: none;
}

.comment-author {
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.comment-content {
  font-size: 14px;
  color: #333;
}

.no-more-comments {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 10px;
}

.comment-input {
  margin-top: 20px;
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 输入框和按钮之间的间距 */
}

.comment-input textarea {
  flex: 1; /* 输入框占据剩余空间 */
  height: 18px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
  color: #333;
}

.comment-input button {
  padding: 8px 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap; /* 防止按钮文字换行 */
}

.comment-input button:hover {
  background-color: #0056b3;
}

/* 点赞图标的动画 */
@keyframes likeAnimation {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 点赞图标点击时的特效 */
.like-animation {
  animation: likeAnimation 0.5s ease-in-out;
}

/* 点赞图标容器 */
.like-icon-container {
  position: relative; /* 设置为相对定位，粒子效果容器将相对于此定位 */
  display: inline-block; /* 确保容器大小与图标一致 */
}

/* 粒子效果容器 */
.particle-container {
  position: absolute; /* 绝对定位，相对于 like-icon-container */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 防止粒子效果容器拦截点击事件 */
}

/* 粒子效果 */
.particle {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #4d636a; /* Bilibili 主题色 */
  border-radius: 50%;
  animation: particleAnimation 1s ease-out;
  transform: translate(var(--x), var(--y)); /* 使用 CSS 变量控制粒子位置 */
}

@keyframes particleAnimation {
  0% {
    transform: translate(0, 0) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(var(--x), var(--y)) scale(0);
    opacity: 0;
  }
}
</style>
